from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import memcache
from domain import userprofile
from repository import baserepository

class UserProfileRepository(baserepository.BaseRepository):

    def getAll(self):
        profiles = db.GqlQuery("SELECT * FROM UserProfile ORDER BY datejoined DESC")
        return profiles

    def getSubscribers(self):
        profiles = db.GqlQuery("SELECT * FROM UserProfile WHERE subscriber=True and enabled=True ORDER BY datejoined DESC")
        return profiles

    def getByUser(self, currentuser):
        if (isinstance(currentuser, users.User)):
            memcache.flush_all()
            cacheduser = memcache.get(currentuser.email())
            if (cacheduser is not None):
                return cacheduser
            else:
                query = db.GqlQuery("SELECT * FROM UserProfile WHERE googleuser = :1 ORDER BY datejoined ASC", currentuser)
                cacheduser = query.get()
                if (cacheduser):
                    memcache.set(cacheduser.googleuser.email(), cacheduser, 3600)
                    return cacheduser
                else:
                    return None

    def getByNickname(self, nickname):
        matches = db.GqlQuery("SELECT * FROM UserProfile WHERE enabled=True AND nickname = :1", nickname)
        return matches.count()

    def save(self, newuserprofile):
        return super(UserProfileRepository, self).save(newuserprofile, userprofile.UserProfile)
        
    def getByKey(self, profilekey):
        return super(UserProfileRepository, self).getByKey(profilekey, userprofile.UserProfile)
